/*
 * @Author: your name
 * @Date: 2021-07-08 21:52:23
 * @LastEditTime: 2021-07-12 20:28:20
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \day1\vue_shop\src\router\index.js
 */
import Vue from 'vue'
import VueRouter from 'vue-router'
import LoginPage from 'views/LoginPage'
import HomePage from 'views/HomePage'
import WelcomePage from 'views/childviews/WelcomePage.vue'
import UserPage from 'views/childviews/UserPage.vue'
import Rights from 'components/power/Rights'
import Roles from 'components/power/Roles'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect:'/loginpage'
  },
  {
    path: '/loginpage',
    component: LoginPage
  },
  {
    path: '/homepage',
    component: HomePage,
    redirect:'/welcomepage',
    children:[{path:'/welcomepage',component:WelcomePage},
    {path:'/users',component:UserPage},
    {path:'/rights',component:Rights},
    {path:'/roles',component:Roles}
  ]
   
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
//挂载路由导航守卫
router.beforeEach((to,from,next)=>{
    //to 将要访问的路径
    //from 代表从哪个路径跳转而来
    //next 是一个函数表示放行
    //next()放行 next('login)
    //如果用户访问的登录页直接放行，如果直接访问的url强制跳转到login
    if(to.path==='/loginpage') return next()
    // 从 sessionStorage 中获取到 保存的 token 值
    const tokenStr=window.sessionStorage.getItem('token')
    //没有token强制跳转到登录页
    if(!tokenStr) return next('/loginpage')
    next()
})
export default router
